package com.lagou.task19;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThread extends Thread{
    Socket socket;

    BufferedReader br = null;
    PrintStream ps = null;
    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //当没有客户端连接时阻塞在此处
        try {

            System.out.println("客户端连接成功");
//        3使用输入输出流进行通信
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            ps = new PrintStream(socket.getOutputStream());
            while (true) {
                String s1 = br.readLine();
                System.out.println("客户端" + socket.getInetAddress() + "发来的内容是： " + s1);
                //回复客户端收到的内容I received
                ps.println("I received");
                if ("bye".equalsIgnoreCase(s1)){
                    System.out.println("聊天结束，关闭服务端");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            4关闭socket并释放有关资源

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
